// @ts-ignore
import { addNamed } from '@babel/helper-module-imports'

export const HELPERS = '\0complugin-plugin-babel-helpers'

export default (function importHelperPlugin({ types: t }: any) {
  return {
    pre(file: any) {
      const cachedHelpers = Object.create(null)
      file.set('helperGenerator', (name: string) => {
        if (!file.availableHelper(name)) {
          return null
        }

        if (cachedHelpers[name]) {
          return t.cloneNode(cachedHelpers[name])
        }

        return (cachedHelpers[name] = addNamed(file.path, name, HELPERS))
      })
    }
  }
})
